<template>
    <el-container>
        <el-header>
            <div class="right-panel-search">
                <div class="search-input">日期</div>
                <el-date-picker v-model="search.time_range" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="medium" style="width:250px" :value-format="'YYYY-MM-DD'" />
                <div class="search-input">部门</div>
                <el-cascader v-model="search.dept_id" :options="depts" :props="deptsProps" clearable></el-cascader>
                <div class="search-input">员工名称</div>
                <el-input v-model="search.name" placeholder="员工名称" clearable @change="upsearch"/>
                <el-button type="primary" icon="el-icon-search" @click="upsearch">搜索</el-button>
                <el-button type="primary" @click="addGrant" :disabled="selection.length==0">批量发放</el-button>
                <el-button type="primary" @click="grantImport" :disabled="selection.length==0">导出工资表</el-button>
                <el-button type="primary" @click="printSalary" :disabled="selection.length==0">批量打印工资明细</el-button>
            </div>
        </el-header>
        <el-main class="nopadding">
            <scTable ref="table" :apiObj="apiObj" @selection-change="selectionChange" stripe remoteSort remoteFilter border :params="query" show-summary>
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="姓名" prop="name" align="center"></el-table-column>
                <el-table-column label="部门" prop="dept_name" align="center"></el-table-column>
                <el-table-column label="岗位" prop="jobs_name" align="center" width="150" column-key="jobs_id" :filters="jobsFilters"></el-table-column>
                <el-table-column label="银行" align="center" width="100">
                    <template #default="{row}">
                        <div>{{row.bank_name}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="银行账号" align="center" width="160">
                    <template #default="{row}">
                        <div>{{row.bank_card}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="工资类型" align="center" width="110">
                    <template #default="scope">
                        <el-tag v-if="scope.row.salary.salary_way==1" type="primary">计时</el-tag>
                        <el-tag v-if="scope.row.salary.salary_way==2" type="success">计件</el-tag>
                        <el-tag v-if="scope.row.salary.salary_way==3" type="danger">计时+ 计件</el-tag>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="应发" prop="total_amount" align="center"></el-table-column>
                <el-table-column label="实发" prop="total_amount" align="center"></el-table-column>
                <el-table-column label="其他" prop="other_amount" align="center"></el-table-column>
                <el-table-column label="补扣" prop="deduction_amount" align="center"></el-table-column> -->
                <el-table-column label="底薪" prop="basic_salary" align="center"></el-table-column>
                <el-table-column label="计件" prop="report_amount" align="center"></el-table-column>
                <el-table-column label="计时" prop="timing_amount" align="center"></el-table-column>
                <el-table-column label="其他" prop="other_amount" align="center"></el-table-column>
                <el-table-column label="应发" prop="total_amount" align="center"></el-table-column>
                <el-table-column label="补扣" prop="deduction_amount" align="center"></el-table-column>
                <el-table-column label="实发" prop="actual_grant_amount" align="center"></el-table-column>
                <el-table-column label="发放状态" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.grant_status==1" type="primary">已发放</el-tag>
                        <el-tag v-if="scope.row.grant_status==0" type="danger">未发放</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" align="center" width="100">
                    <template #default="scope">
                        <el-button-group style="display:flex;flex-direction:column">
                            <el-button text type="primary" size="small" @click="table_show(scope.row, scope.$index)" v-auth="'salary.show'">查看明细</el-button>
                            <el-button text type="primary" size="small" @click="table_input(scope.row, scope.$index)" v-auth="'salary.input'">录入</el-button>
                            <!-- <el-button text type="primary" size="small" @click="table_grant(scope.row, scope.$index)" v-auth="'salary.grant'">工资发放</el-button> -->
                        </el-button-group>
                    </template>
                </el-table-column>
            </scTable>
        </el-main>
    </el-container>
	<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save = false" draggable></save-dialog>
    <salary-detail v-if="dialog.detail" ref="detailDialog" @success="handleSuccess" @closed="dialog.detail = false" draggable :query="{staff_id:this.staff_id}"></salary-detail>
    <salary-print v-if="dialog.print" ref="printDialog" @success="handleSuccess" @closed="dialog.print = false" draggable></salary-print>
    <el-dialog v-model="dialog.sort" title="请选择打印排序" width="500" :before-close="handleClose" align-center>
        <el-radio-group v-model="printType" class="ml-4" @change="radioChange">
            <el-radio label="1" size="large">按天排序</el-radio>
            <el-radio label="2" size="large">按工厂货号排序</el-radio>
        </el-radio-group>
    </el-dialog>
</template>

<script>
import SalaryDetail from './salaryDetail.vue'
import SalaryPrint from './salaryPrint.vue'
import saveDialog from './save'

export default {
	name: 'user',
	components: {saveDialog,SalaryDetail,SalaryPrint,},
	data() {
		return {
			dialog: {
				save: false,
                detail:false,
                print:false,
                sort:false,
			},
			apiObj: this.$API.inventory.staffSalary.list,
			selection: [],
			search: {
				dept_id: null,
                time_range: [this.moment().startOf('month').format('YYYY-MM-DD'), this.moment().endOf('month').format('YYYY-MM-DD')],
			},
            query:{
                time_range:[this.moment().startOf('month').format('YYYY-MM-DD'), this.moment().endOf('month').format('YYYY-MM-DD')],
            },
            staffList:[],
            staff_id:"",
            depts: [],
			deptsProps: {
				value: "id",
				checkStrictly: true
			},
            printType:'',
            eOp:'',
            jobsFilters:[],
		}
	},
	mounted() {
        this.getDept()
        this.getFilter()
	},
	methods: {
        // 获取部门
        async getDept() {
			var res = await this.$API.system.dept.list.get();
			this.depts = res.data;
		},
        async getFilter() {
            var res = await this.$API.all.getProduceFilter.get({place:6});
			let jobs = []
            res.data.job_list.map(item => {
				jobs.push({
					text: item.name,
					value: item.id,
				})
			})
			this.jobsFilters = jobs
		},
		//查看明细
		table_show(row) {
            this.staff_id = row.id
			this.dialog.detail = true
			this.$nextTick(() => {
				this.$refs.detailDialog.open('show').setData(row)
			})
		},
        // 录入
        table_input(row) {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('edit').setData(row)
			})
		},
		// jit批量删除
		async addGrant() {
			var delete_ids = [];
			this.selection.forEach((item) => {
				delete_ids.push(item.id);
			});
			this.$confirm(
				`确定发放选中的 ${this.selection.length} 项吗？`,
				"提示",
				{
					type: "warning",
				}
			)
				.then(() => {
					this.jit_del_all(delete_ids);
				})
				.catch(() => { });
		},
        async jit_del_all(delete_ids) {
			var reqData = { ids: delete_ids, time_range:this.search.time_range};
			var res = await this.$API.inventory.staffSalary.grant.post(reqData);
			if (res.code == 1) {
				this.$message.success("发放成功");
                this.$refs.table.refresh()
			} else {
				this.$alert(res.message, "提示", { type: "error" });
			}
		},
        grantImport(){
            var delete_ids = [];
			this.selection.forEach((item) => {
				delete_ids.push(item.id);
			});
            this.dialog.sort = true
            this.eOp = 'export'
			// this.$confirm(
			// 	`确定导出选中的 ${this.selection.length} 位员工的工资表吗？`,
			// 	"提示",
			// 	{
			// 		type: "warning",
			// 	}
			// )
			// 	.then(() => {
			// 		this.it(delete_ids);
			// 	})
			// 	.catch(() => { });
        },
        async it(delete_ids) {
			var reqData = { staff_id: delete_ids, time_range:this.search.time_range,type:this.printType};
			var res = await this.$API.inventory.staffDeduc.salaryExport.get(reqData);
            if (res.code == 1) {
                if(res.data.rows !=''){
                    const fileUrl = res.data.rows.url;
                    const link = document.createElement("a");
                    link.href = fileUrl;
                    link.download = fileUrl;
                    link.click();
                }else{
                    this.$alert("请求异常", "提示", { type: "error" });
                }
                this.dialog.sort = false;
                this.printType = ''
			} else {
				this.$alert(res.message, "提示", { type: "error" });
			}
		},
        async printSalary(){
            this.dialog.sort = true;
            this.eOp = 'print'
            // var delete_ids = [];
			// this.selection.forEach((item) => {
			// 	delete_ids.push(item.id);
			// });
            // var reqData = { staff_id: delete_ids, time_range:this.search.time_range};
            // this.dialog.print = true
			// this.$nextTick(() => {
			// 	this.$refs.printDialog.open('show').setData(reqData)
			// })

            // var delete_ids = [];
			// this.selection.forEach((item) => {
			// 	delete_ids.push(item.id);
			// });
            // var reqData = { staff_id: delete_ids, time_range:this.search.time_range};
			// var res = await this.$API.inventory.staffDeduc.salaryExport.get(reqData);
            // if (res.code == 1) {
            //     if(res.data.rows !=''){
            //         const fileUrl = res.data.rows.url;
            //         const link = document.createElement("a");
            //         link.href = fileUrl;
            //         link.download = fileUrl;
            //         link.click();
            //     }else{
            //         this.$alert("请求异常", "提示", { type: "error" });
            //     }
			// } else {
			// 	this.$alert(res.message, "提示", { type: "error" });
			// }
        },
        radioChange(){
            var delete_ids = [];
            this.selection.forEach((item) => {
                delete_ids.push(item.id);
            });
            if(this.eOp=='export'){
                this.it(delete_ids);
            }else{
                var reqData = { staff_id: delete_ids, time_range:this.search.time_range,type:this.printType};
                this.dialog.sort = false;
                this.dialog.print = true
                this.printType = ''
                this.$nextTick(() => {
                    this.$refs.printDialog.open('show').setData(reqData)
                })
            }
        },
		//搜索
		upsearch() {
			this.$refs.table.upData(this.search)
		},
        selectionChange(selection) {
			this.selection = selection;
		},
		//本地更新数据
		handleSuccess(data, mode) {
			if (mode == 'add') {
				this.$refs.table.refresh()
			} else if (mode == 'edit') {
				this.$refs.table.refresh()
			} else if (mode == 'set') {
				this.$refs.table.refresh()
			}
		},
        // 获取员工
        async getStaff() {
			var res = await this.$API.all.staff.get();
			this.staffList = res.data;
		},
	}
}
</script>

<style>
.search-input {
	width: auto;
	font-size: 14px;
}
</style>
